/*
我自己在这个文件中对 express 进行测试。
*/
var http_port = 8000,https_port = 44300

var express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var sqlite3 = require('sqlite3').verbose();
var log4js = require("log4js")
log4js.configure({
    appenders:[
        { type:"file", filename:"logs/visit.log",maxLogSize:1024*1024,backups:100 }
    ]
})
var logger = log4js.getLogger("normal")

var options = {
    key: fs.readFileSync('ssl/2_asay.pub.key'),
    cert: fs.readFileSync('ssl/1_asay.pub_bundle.crt')
};
var app = express();
app.set('x-powered-by', 'My Site');

https.createServer(options, app).listen(https_port, function() {
    logger.info('https server started successfully, at port %d.',https_port);
});

http.createServer(app).listen(http_port, function() {
    logger.info('http server started successfully, at post %d.',http_port);
});

app.use(function (req, res,next){
	var ip =  req['ip']
	var path = req['path']
	var time = new Date().getTime()
    logger.info("visit ---- path:%s,time:%s,ip:%s ",path,time,ip);
	var db = new sqlite3.Database('haha.db', function (error){ 
		if(!error){
			db.serialize(function() {
				var stmt = db.prepare('INSERT INTO infos (ip,path,time)  VALUES (?,?,?)');
				stmt.run(ip,path,time);
				stmt.finalize();
			});
			db.close();
		}
	});
	next();
});
app.use(express.static(__dirname + '/public'));

var dgz = require("./api_dgz")
app.use("/dgz",dgz);

// 匹配根路径的请求
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

// 匹配 /about 路径的请求
app.get('/about', function (req, res) {
    res.send('about');
});

// 匹配 /random.text 路径的请求
app.get('/random.text', function (req, res) {
    res.send('random.text');
});

// 匹配 /baidu ,重定向到 http://www.baidu.com
app.get('/baidu', function (req, res) {
    res.redirect('http://www.baidu.com');
});

// 匹配 /toabout ,重定向到 /about
app.get('/toabout', function (req, res) {
    res.redirect('/about');
});

// 匹配 /json ,重定向到 /about
app.get('/json', function (req, res) {
    var json = {}
    json.name = 'haha'
    json.age = 12
    json.childs = ['xiao1','xiao2',97,63]
    res.json(json);
});

app.get('/info', function (req, res) {
	var obj = {}
	function add(name){
		obj[name] = req[name]
	}
	add('hostname')
	add('ip')
	add('cookies')
	add('baseUrl')
	add('body')
	add('fresh')
	add('originalUrl')
	add('params')
	add('path')
	add('protocol')
	add('query')
	add('get')
	add('is')
	res.json(obj);
});

app.get('/history', function (req, res) {
	var num = req.query.num || 10
	var db = new sqlite3.Database('haha.db', function (error){ 
			if(!error){
				var list = new Array();
				db.each('select * from infos order by id desc limit ' + num, function(err, row) {
					var item = {id:row.id,ip: row.ip,path:row.path,time:row.time}
					list.push(item);
				},function(){
					res.json(list);
					db.close();
				});
			}
	});
});
